/******************************************************************************
 * @File name   :      ProxyConn.java
 *
 * @Author      :      Brenda Yin
 *
 * @Date        :      2012-6-15
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2012-6-15 下午09:11:48        Brenda Yin     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

import com.cap.bts.framework.common.exception.AppException;

public class ConnProxy implements InvocationHandler{

	private Connection conn;
	
	public ConnProxy(Connection Connection){
		this.conn = Connection;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		if(method.getName().equals("prepareStatement")){
			if(args!=null&&args.length>0){
				String argsSQL= (String)args[0];
				if(argsSQL.toUpperCase().indexOf("UPDATE TM_MK_OPPORTUNITY SET ") > -1){
					//REPLACE WITH APPEND SQL PARAMS
					try {
						long current = System.currentTimeMillis();
						args[0] = argsSQL + " and " + current + " = " + current;
						Object obj = method.invoke(conn,args);

//	 					PreparedStatement stmt = (PreparedStatement)obj;
//						obj = Proxy.newProxyInstance(stmt.getClass().getClassLoader(), new Class[]{PreparedStatement.class}, new StmtProxy(stmt));

						return obj;
					} catch (Exception e) {
						throw new AppException("ProxyConn invoke error!", e);
					}
				} else if(argsSQL.toUpperCase().indexOf("INSERT INTO TI_MK_OPTY_UPLD_OUT") > -1){
					//REPLACE WITH APPEND SQL PARAMS
					try {
						long current = System.currentTimeMillis();
						String upperSql = argsSQL.toUpperCase();
						int index = upperSql.indexOf("INTO TI_MK_OPTY_UPLD_OUT");
						String prefixSql = "INSERT /*+ " + current + " */ ";		
						args[0] = prefixSql + upperSql.substring(index);
						Object obj = method.invoke(conn,args);
						return obj;
					} catch (Exception e) {
						throw new AppException("ProxyConn invoke error!", e);
					}
				} else {
					return method.invoke(conn,args);
				}
			}
		}
		return method.invoke(conn,args);
	}
}

